package com.itbbfx.controller.warehourse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itbbfx.entity.*;
import com.itbbfx.service.pharmacymanager.DrugdictionaryService;
import com.itbbfx.service.pharmacymanager.PharmacyService;
import com.itbbfx.service.pharmacymanager.RecordService;
import com.itbbfx.service.warehourse.AreaService;
import com.itbbfx.service.warehourse.BaoqueService;
import com.itbbfx.service.warehourse.DrugstoreService;
import com.itbbfx.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController {
    @Autowired
    private RecordService recordservice;
    @Autowired
    private DrugdictionaryService drugdictionaryService;
    @Autowired
    private DrugstoreService drugstoreService;
    @Autowired
    private BaoqueService baoqueService;
    @Autowired
    private PharmacyService pharmacyService;
    @Autowired
    private AreaService areaService;

    /**
     * 查询操作记录
     *
     * @param page
     * @param limit
     * @param record
     * @return
     */
    @RequestMapping("/selrecord")
    public DataGridView selRecord(Integer page, Integer limit, Record record) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(recordservice.selRecord(record));
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 药品入库
     *
     * @param record
     * @param drugstore
     * @return
     */
    @RequestMapping("/addDrugs")
    public int addDrugs(Record record, Drugstore drugstore,HttpSession session) {
        record.setJilutime(new Date());
        record.setJiluPeople(((User)(session.getAttribute("user"))).getUserid().toString());
        if (recordservice.addRecord(record) > 0) {
            return drugstoreService.addDrugstoreNum(drugstore);
        }

        return 0;
    }

    /**
     * 查询药品字典
     *
     * @return
     */
    @RequestMapping("/selectdgty")
    public DataGridView selectdgty(Integer page, Integer limit, String drugName) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(drugdictionaryService.selectdgty(new Drugdictionary(drugName)));
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 查询仓库中药品剩余数量
     *
     * @param drugstoreName
     * @param warehouseId
     * @return
     */
    @RequestMapping("/selnumber")
    public Object selnumber(String drugstoreName, Integer warehouseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("medicineid", IdWorker.getNextId(1, 1, 1));
        map.put("number", drugdictionaryService.selnumber(drugstoreName, warehouseId));
        return map;
    }

    /**
     * 查询药房缺失的药品
     *
     * @return
     */
    @RequestMapping("/selbaoquedan")
    public DataGridView selbaoquedan(Integer page, Integer limit, Baoque baoque) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(baoqueService.queryAll(baoque));
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 查询库房的药品
     *
     * @return
     */
    @RequestMapping("/selectdrugstore")
    public DataGridView selectdrugstore(Integer page, Integer limit, Drugstore drugstore) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(drugstoreService.queryDrugstore(drugstore));
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 药品出库
     *
     * @param ypharmacy 药房 药品
     * @param record    出库记录
     * @return
     */
    @RequestMapping("/addpharmacy")
    public int addPharmacy(Integer rugstoreId, Ypharmacy ypharmacy, Record record, HttpSession session) {
        String batch = new IdWorker(1, 1, 1).nextId() + "";
        record.setJilutime(new Date());
        record.setJilupihao(batch);
        record.setJiluPeople(((User) session.getAttribute("user")).getRealname());

        int userid = ((User) session.getAttribute("user")).getUserid();
        Drugstore drugstore = new Drugstore();
        drugstore.setSkullId(userid);
        drugstore.setRugstoreId(rugstoreId);
        drugstore.setDrugstorenum(record.getJilunumber());
        drugstore.setBatch(batch);

        ypharmacy.setSkullId(userid);
        ypharmacy.setSkullbatch(batch);
        return updatePharmacy(record, drugstore, ypharmacy);
    }

    /**
     * 药品补给
     *
     * @param drugstore
     * @param record
     * @param session
     * @return
     */
    @RequestMapping("/updatedrugnumber")
    public int updateDrugnumber(Drugstore drugstore, Ypharmacy ypharmacy, Record record, HttpSession session) {
        String batch = new IdWorker(1, 1, 1).nextId() + "";
        record.setJilutime(new Date());
        record.setJilupihao(batch);
        User user = ((User) session.getAttribute("user"));
        record.setJiluPeople(user.getRealname());

        drugstore.setSkullId(user.getUserid());
        drugstore.setBatch(batch);

        ypharmacy.setSkullId(user.getUserid());
        ypharmacy.setSkullbatch(batch);
        return updatePharmacy(record, drugstore, ypharmacy);
    }

    private int updatePharmacy(Record record, Drugstore drugstore, Ypharmacy ypharmacy) {
        // 添加出库记录
        recordservice.addRecord(record);
        // 更新仓库药品数量
        drugstoreService.exWarehouse(drugstore);
        // 删除报缺记录
        Baoque baoque = baoqueService.queryBaoque(record.getJiluname());
        if (baoque != null) {
            baoqueService.clean(baoque, record.getJilunumber());
        }
        return pharmacyService.addPharmacy(ypharmacy);// 添加到药房
    }


    /**
     * 查询过期药品
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/seldrugDateguoqi")
    public DataGridView seldrugDateguoqi(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(drugstoreService.queryOverdue());
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 销毁过期药品
     *
     * @param record     销毁记录
     * @param rugstoreId 药品仓库 药品Id
     * @return
     */
    @RequestMapping("/delguoqidurg")
    public int delguoqidurg(Record record, Integer rugstoreId, HttpSession session) {
        record.setJilutime(new Date());
        record.setJiluPeople(((User) session.getAttribute("user")).getRealname());
        if (recordservice.addRecord(record) > 0) {
            return drugstoreService.delDrugstore(rugstoreId);
        }

        return 0;
    }

    @RequestMapping("/selbaoquedrugname")
    private DataGridView selbaoquedrugname(String drugstoreName, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo(drugstoreService.queryDrugstore(new Drugstore(drugstoreName)));
        return new DataGridView(pageInfo.getTotal(), pageInfo.getList());
    }

// --------------------------------------------------------------------------------------------------------------

    /*
     * 查询生产地址
     * */
    @RequestMapping("findAllAreas")
    public Object AreaList(Area Area, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Area> listAll = areaService.findAllArea(Area);
        PageInfo pageInfo = new PageInfo(listAll);
        Map<String, Object> tableData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", pageInfo.getList());

        return tableData;
    }

    /*
     * 添加生产地址
     * */
    @RequestMapping("addArea")
    public Object addArea(Area Area) {
        int count = areaService.count(Area);
        if (count == 0) {
            int i = areaService.addArea(Area);
            if (i == 1) {
                return "添加成功";
            } else {
                return "添加失败";
            }
        } else {
            return Area.getAreaName() + "已存在";
        }

    }

    /*
     * 删除生产地址
     * */
    @RequestMapping("deleteArea")
    public Object deleteArea(Integer areaId) {
        int i = areaService.deleteArea(areaId);
        if (i == 1) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    //    药品字典
    /*
     * 查询药品
     * */
    @RequestMapping("findAllSdrugdictionary")
    public Object SdrugdictionaryList(Drugdictionary sdrugdictionary, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Drugdictionary> listAll = drugdictionaryService.selectdgty(sdrugdictionary);
        PageInfo pageInfo = new PageInfo(listAll);
        Map<String, Object> tableData = new HashMap();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", pageInfo.getList());

        return tableData;
    }

    /*
     * 添加药品
     * */
    @RequestMapping("addSdrugdictionary")
    public Object addSdrugdictionary(Drugdictionary sdrugdictionary) {
        int count = drugdictionaryService.count(sdrugdictionary);
        if (count == 0) {
            int i = drugdictionaryService.addSdrugdictionary(sdrugdictionary);
            if (i == 1) {
                return "添加成功";
            } else {
                return "添加失败";
            }
        } else {
            return sdrugdictionary.getDrugName() + "已存在";
        }

    }

    /*
     * 修改药品
     * */
    @RequestMapping("editSdrugdictionary")
    public Object editSdrugdictionary(Drugdictionary sdrugdictionary) {
        int i = drugdictionaryService.editSdrugdictionary(sdrugdictionary);
        if (i == 1) {
            return "修改成功";
        } else {
            return "修改失败";
        }

    }

    /*
     * 删除药品
     * */
    @RequestMapping("deleteSdrugdictionary")
    public Object deleteSdrugdictionary(Integer drugId) {
        int i = drugdictionaryService.deleteSdrugdictionary(drugId);
        if (i == 1) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @RequestMapping("findAllArea")
    public Object findAllArea() {
        List<Area> allArea = drugdictionaryService.findAllArea();
        return allArea;
    }

    @RequestMapping("findAllTypes")
    public Object findAllType() {
        List<Type> allType = drugdictionaryService.findAllType();
        return allType;
    }

    @RequestMapping("findAllUnits")
    public Object findAllUnit() {
        List<Unit> allUnit = drugdictionaryService.findAllUnit();
        return allUnit;
    }

    //查询药品类型
    @RequestMapping("seltype")
    public Object seltype(Type type) {
        List<Type> seltype = drugstoreService.seltype(type);
        return seltype;
    }

    //查询计量单位
    @RequestMapping("selunit")
    public Object selunit(Unit unit) {
        List<Unit> selunit = drugstoreService.selunit(unit);
        return selunit;
    }

    //查询产地
    @RequestMapping("selarea")
    public Object selarea(Area area) {
        List<Area> selarea = drugstoreService.selarea(area);
        return selarea;
    }

    //查询经办人
    @RequestMapping("selskull")
    public Object selskull(Skull skull) {

        List<Skull> selskull = drugstoreService.selskull(skull);

        return selskull;
    }

    //查询供货商
    @RequestMapping("selupplier")
    public Object selupplier(Upplier upplier, Model model) {
        List<Upplier> selupplier = drugstoreService.selupplier(upplier);
        return selupplier;
    }

    //修改库房药品基本信息
    @RequestMapping("updrug")
    public Object updrugstore(Drugstore drugstore) {
        int add = drugstoreService.updrugstore(drugstore);
        if (add == 1) {
            return "修改成功";
        } else {
            return "修改失败";
        }
    }

    //供货商
    @RequestMapping("bpisselupplier")
    public Object bpisselupplier(Upplier upplier, Model model) {

        List<Upplier> selupplier = drugstoreService.selupplier(upplier);
        return "drugstore/c_beputinstorage";
    }

    //查询仓库里药品数量不足的药品
    @RequestMapping("selectlackdrug")
    public Object selectlackdrug(Drugstore drugstore, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Drugstore> drugstores = drugstoreService.selectlackdrug(drugstore);//查询药品数量不足的药
        PageInfo pageInfo = new PageInfo(drugstores);
        Map<String, Object> drugstoresData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        drugstoresData.put("code", 0);
        drugstoresData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        drugstoresData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        drugstoresData.put("data", pageInfo.getList());
        return drugstoresData;
    }

    //查询采购单
    @RequestMapping("selcaigou")
    public Object selcaigou(Caigou caigou, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Caigou> caigous = drugstoreService.selcaigou(caigou);//查询遍历采购表
        PageInfo pageInfo = new PageInfo(caigous);
        Map<String, Object> drugstoresData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        drugstoresData.put("code", 0);
        drugstoresData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        drugstoresData.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        drugstoresData.put("data", pageInfo.getList());
        return drugstoresData;
    }

    //添加一条药品采购单
    @RequestMapping("addcaigou")
    public Integer addcaigou(Caigou caigou) {
        int selcaigouname = drugstoreService.selcaigouname(caigou);//查询采购单是是否已经存在此条数据
        if (selcaigouname == 0) {
            int seldrugname = drugstoreService.addcaigou(caigou);//添加
            return seldrugname;
        } else {
            int upcaigounumber = drugstoreService.upcaigounumber(caigou);//修改
            return upcaigounumber;
        }

    }

    //删除一条药品采购单
    @RequestMapping("delcaigou")
    public Integer delcaigou(Integer caigouid) {
        int seldrugname = drugstoreService.delcaigou(caigouid);//删除此条采购数据
        return seldrugname;
    }
}